﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Web.Mvc;
using System.Web.Security;
using Ornament.MemberShip;
using Ornament.MemberShip.Permissions;
using Ornament.MVCWebFrame.Models;
using Ornament.MVCWebFrame.Models.MemberShips;
using Ornament.Web;
using Ornament.Web.Mvc;
using Ornament.Web.Mvc.JQuery.JQGrid;

namespace Ornament.MVCWebFrame.Areas.MemberShips.Controllers
{
    /// <summary>
    /// </summary>
    [Authorize(Users = "admin")]
    public class UserController : Controller
    {
        // GET: /Reader/

        /// <summary>
        /// </summary>
        /// <returns>
        /// </returns>
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Edit(string id)
        {
            ViewData.Model = OrnamentContext.Current.MemberShipFactory.CreateUserDao().Get(id);
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(string id, FormCollection collection)
        {
            IUserDao dao = OrnamentContext.Current.MemberShipFactory.CreateUserDao();
            User editngUser = dao.Get(id);

            editngUser.Email = collection["Email"];
            editngUser.Information.Name = collection["Name"];
            editngUser.Comment = collection["Comment"];
            editngUser.Information.Phone = collection["Phone"];
            editngUser.IsApproved = collection["IsApproved"].StartsWith("true");
            editngUser.IsLockout = collection["IsLockout"].StartsWith("true");
            //set roles;

            editngUser.ClearRole();
            string[] roleNames = collection["assignRoles"].Split(new[] {","}, StringSplitOptions.RemoveEmptyEntries);
            if (roleNames.Length != 0)
            {
                ReadOnlyCollection<Role> roles =
                    OrnamentContext.Current.MemberShipFactory.CreateRoleDao().GetRoles(roleNames);
                foreach (var role in roles)
                {
                    editngUser.AddRole(role);
                }
            }
            
            dao.SaveOrUpdate(editngUser);
            return RedirectToAction("Index");
        }

        /// <summary>
        /// </summary>
        /// <param name="submitData">
        /// The submit Data.
        /// </param>
        /// <returns>
        /// </returns>        
        public ActionResult GetUsers([ModelBinder(typeof (JQGridSubmitDataBinder))] JQGridSubmitData submitData)
        {
            IUserDao dao = OrnamentContext.Current.MemberShipFactory.CreateUserDao();
            IList<User> users = dao.FindAll(submitData.PageIndex - 1, submitData.PageSize);

            JQGridResult result = submitData.Create();
            result.total = dao.CountAll();

            foreach (User u in users)
            {
                result.rows.Add(new JQItem
                                    {
                                        id = u.LoginId,
                                        cell = new ArrayList
                                                   {
                                                       u.LoginId,
                                                       u.Information.Name,
                                                       u.Email,
                                                       u.IsLockout ? "是" : "否",
                                                       u.IsApproved ? "是" : "否"
                                                   }
                                    });
            }
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="searchValue"></param>
        /// <returns></returns>
        [JsonContainerFilter]
        public ActionResult Search(JsonContainer searchValue)
        {
            var result = from u in OrnamentContext.Current.MemberShipFactory.Users
                             .Take(searchValue.ToInt32("pageSize"))
                             .Skip(searchValue.ToInt32("pageIndex")*searchValue.ToInt32("pageSize"))
                         where
                             u.LoginId.StartsWith(searchValue.ToString("loginId"))
                         select new
                                    {
                                        u.Information.Name,
                                        u.LoginId
                                    };
            return Json(result);
        }

        public ActionResult CreateWizard()
        {
            return View();
        }

        [JsonContainerFilter]
        public ActionResult Create(JsonContainer user)
        {
            try
            {
                MembershipUser result;
                MembershipCreateStatus status;
                if (Membership.RequiresQuestionAndAnswer)
                {
                    result = Membership.CreateUser(
                        user.ToString("LoginId"),
                        user.ToString("Password"),
                        user.ToString("Email"),
                        user.ToString("Question"),
                        user.ToString("Answer"), true, out status);
                }
                else
                {
                    result = Membership.CreateUser(
                        user.ToString("LoginId"),
                        user.ToString("Password"), user.ToString("Email")
                        );
                }

                User savedUser = OrnamentContext.Current.MemberShipFactory.CreateUserDao().Get(result.UserName);
                savedUser.Information.Name = user.ToString("Name");
                savedUser.Information.Phone = user.ToString("Phone");
                savedUser.Comment = user.ToString("Comment");

                return Json(new ReturnResult("创建成功", true));
            }
            catch (Exception ex)
            {
                return Json(new ReturnResult(ex.Message, false));
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="userName"></param>
        /// <returns></returns>
        public ActionResult IsExit(string userName)
        {
            IUserDao dao = OrnamentContext.Current.MemberShipFactory.CreateUserDao();
            bool exist = dao.Get(userName) != null;
            var o = new
                        {
                            Result = exist
                        };
            return base.Json(o, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        public ActionResult EmailIsExist(string email)
        {
            IUserDao dao = OrnamentContext.Current.MemberShipFactory.CreateUserDao();
            return base.Json(dao.GetUserByEmail(email) != null);
        }

        [ResourceAuthorize(UserOperator.Lock, "Reader")]
        public ActionResult UnlockUser(string loginId)
        {
            IUserDao dao = OrnamentContext.Current.MemberShipFactory.CreateUserDao();
            foreach (string loginid in loginId.Split(','))
            {
                User user = dao.Get(loginid);
                user.IsLockout = false;
            }
            return Json(new ReturnResult("成功解锁以下用户" + loginId, true));
        }

        [ResourceAuthorize(UserOperator.Approve, "Reader")]
        public ActionResult Approve(string loginId)
        {
            IUserDao dao = OrnamentContext.Current.MemberShipFactory.CreateUserDao();
            foreach (string loginid in loginId.Split(','))
            {
                User user = dao.Get(loginid);
                user.IsApproved = true;
            }
            return Json(new ReturnResult("成功激活以下用户" + loginId, true));
        }

        [ResourceAuthorize(UserOperator.SetPassword, "Reader")]
        public ActionResult ResetPassword(string loginId)
        {
            var privoder = Membership.Provider as MemberShipProvider;
            User user = OrnamentContext.Current.MemberShipFactory.CreateUserDao().Get(loginId);
            string newpassword = Membership.GeneratePassword(Membership.MinRequiredPasswordLength, 0);

            user.ChangePassword(privoder.EncodeString(newpassword, privoder.PasswordFormat));

            OrnamentContext.Current.MemberShipFactory.CreateUserDao().SaveOrUpdate(user);
            return Json(newpassword);
        }
    }
}